#include "backbookindex.h"
#include "../utils/fileutils.h"
#include <ostream>
#include <fstream>
#include <algorithm>

using namespace std;

BackBookIndex::BackBookIndex(const BackBookIndex& other)
{
    words = other.words;
}

bool BackBookIndex::addWord(Word word, int page)
{
    for(vector<Word>::iterator it = words.begin(); it != words.end(); it++)
    {
        if(it->data == word.data)
        {
            it->occurrences.insert(page);
            return true;
        }
    }
    word.occurrences.insert(page);
    words.push_back(word);
    return true;
}

void BackBookIndex::write(const char* output) throw (FileException)
{
    sort(words.begin(), words.end());
    
    if(!output)
        throw NullPathException();
    ofstream out(output);
    if(!out.good())
        throw OpenFileException(output);
    
    vector<Word>::iterator wordsIt = words.begin();
    for (; wordsIt != words.end(); wordsIt++)
    {
        out << wordsIt->data << ": ";
        set<int>::iterator occurrencesIt = wordsIt->occurrences.begin();
        for (unsigned int i = 0; i < wordsIt->occurrences.size(); i++)
        {
            out << *occurrencesIt;
            if(i != wordsIt->occurrences.size() - 1)
            {
                out << ", ";
            }
            occurrencesIt++;
        }
        out << endl;
    }
    out.close();
}
